document.addEventListener('DOMContentLoaded', function() {
    const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content');
    const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content');
    
    // 地址模态框相关元素
    const addressModal = new bootstrap.Modal(document.getElementById('addressModal'));
    const addressForm = document.getElementById('addressForm');
    const addressModalTitle = document.getElementById('addressModalTitle');
    const saveAddressBtn = document.getElementById('saveAddressBtn');
    let isEditingAddress = false;
    let currentAddressId = null;

    const profileForm = document.getElementById('profileForm');
    const saveProfileBtn = document.getElementById('saveProfileBtn');
    const profileMessage = document.getElementById('profileMessage');

    if (profileForm && saveProfileBtn) {
        profileForm.addEventListener('submit', function(event) {
            event.preventDefault(); // 阻止表单默认提交行为

            const userId = document.getElementById('userId').value;
            const username = document.getElementById('username').value.trim();
            const phoneNumber = document.getElementById('phoneNumber').value.trim();
            const realName = document.getElementById('realName').value.trim();

            // 基本验证
            if (!username) {
                profileMessage.className = 'alert alert-danger';
                profileMessage.textContent = '用户名不能为空';
                return;
            }
            if (!phoneNumber) {
                profileMessage.className = 'alert alert-danger';
                profileMessage.textContent = '手机号码不能为空';
                return;
            }
            if (!realName) {
                profileMessage.className = 'alert alert-danger';
                profileMessage.textContent = '真实姓名不能为空';
                return;
            }
            // 简单的手机号格式验证
            const phoneRegex = /^1[3-9]\d{9}$/;
            if (!phoneRegex.test(phoneNumber)) {
                profileMessage.className = 'alert alert-danger';
                profileMessage.textContent = '请输入正确的手机号码格式';
                return;
            }

            const updatedProfile = {
                id: userId,
                username: username,
                phoneNumber: phoneNumber,
                realName: realName
            };

            fetch('/profile/update', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    [csrfHeader]: csrfToken
                },
                body: JSON.stringify(updatedProfile)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    profileMessage.className = 'alert alert-success';
                    
                    if (data.usernameChanged) {
                        // 如果修改了用户名，显示特殊提示并在3秒后跳转到登录页
                        profileMessage.innerHTML = data.message + '<br/><strong>由于用户名已更改，3秒后将自动跳转到登录页面。</strong>';
                        setTimeout(() => {
                            // 直接跳转到登录页面，让用户重新登录
                            window.location.href = '/login?logout';
                        }, 3000);
                    } else {
                        // 如果没有修改用户名，显示成功消息并在2秒后刷新页面
                        profileMessage.textContent = data.message;
                        setTimeout(() => {
                            location.reload();
                        }, 2000);
                    }
                } else {
                    profileMessage.className = 'alert alert-danger';
                    profileMessage.textContent = data.message;
                }
            })
            .catch(error => {
                console.error('Error updating profile:', error);
                profileMessage.className = 'alert alert-danger';
                profileMessage.textContent = '更新个人资料失败，请稍后再试。';
            });
        });
    }

    const changePasswordForm = document.getElementById('changePasswordForm');
    const changePasswordBtn = document.getElementById('changePasswordBtn');
    const passwordMessage = document.getElementById('passwordMessage');

    if (changePasswordForm && changePasswordBtn) {
        changePasswordForm.addEventListener('submit', function(event) {
            event.preventDefault(); // 阻止表单默认提交行为

            const oldPassword = document.getElementById('oldPassword').value;
            const newPassword = document.getElementById('newPassword').value;
            const confirmNewPassword = document.getElementById('confirmNewPassword').value;

            if (newPassword !== confirmNewPassword) {
                passwordMessage.className = 'alert alert-danger';
                passwordMessage.textContent = '两次输入的新密码不一致。';
                return;
            }

            if (newPassword.length < 6) { // 简单密码长度验证
                passwordMessage.className = 'alert alert-danger';
                passwordMessage.textContent = '新密码长度不能少于6位。';
                return;
            }

            const passwordData = {
                oldPassword: oldPassword,
                newPassword: newPassword,
                confirmNewPassword: confirmNewPassword
            };

            fetch('/profile/change-password', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    [csrfHeader]: csrfToken
                },
                body: JSON.stringify(passwordData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    passwordMessage.className = 'alert alert-success';
                    passwordMessage.textContent = data.message;
                    // 清空密码字段
                    document.getElementById('oldPassword').value = '';
                    document.getElementById('newPassword').value = '';
                    document.getElementById('confirmNewPassword').value = '';
                    
                    // 3秒后自动隐藏成功消息
                    setTimeout(() => {
                        passwordMessage.className = '';
                        passwordMessage.textContent = '';
                    }, 3000);
                } else {
                    passwordMessage.className = 'alert alert-danger';
                    passwordMessage.textContent = data.message;
                }
            })
            .catch(error => {
                console.error('Error changing password:', error);
                passwordMessage.className = 'alert alert-danger';
                passwordMessage.textContent = '更改密码失败，请稍后再试。';
            });
        });
    }

    // 地址管理功能
    // 添加地址按钮
    document.getElementById('addAddressBtn').addEventListener('click', function() {
        isEditingAddress = false;
        currentAddressId = null;
        addressModalTitle.textContent = '添加地址';
        addressForm.reset();
        addressModal.show();
    });

    // 编辑地址按钮
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('edit-address-btn')) {
            const addressId = e.target.getAttribute('data-address-id');
            editAddress(addressId);
        }
    });

    // 设为默认按钮
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('set-default-btn')) {
            const addressId = e.target.getAttribute('data-address-id');
            setDefaultAddress(addressId);
        }
    });

    // 删除地址按钮
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('delete-address-btn')) {
            const addressId = e.target.getAttribute('data-address-id');
            deleteAddress(addressId);
        }
    });

    // 保存地址
    saveAddressBtn.addEventListener('click', function() {
        const addressData = {
            address: document.getElementById('addressText').value,
            isDefault: document.getElementById('isDefault').checked
        };

        if (isEditingAddress) {
            addressData.id = currentAddressId;
            updateAddress(addressData);
        } else {
            addAddress(addressData);
        }
    });

    // 添加地址函数
    function addAddress(addressData) {
        fetch('/profile/address/add', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                [csrfHeader]: csrfToken
            },
            body: JSON.stringify(addressData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                addressModal.hide();
                location.reload(); // 刷新页面显示新地址
            } else {
                alert('添加地址失败：' + data.message);
            }
        })
        .catch(error => {
            console.error('Error adding address:', error);
            alert('添加地址失败，请稍后再试。');
        });
    }

    // 更新地址函数
    function updateAddress(addressData) {
        fetch('/profile/address/update', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                [csrfHeader]: csrfToken
            },
            body: JSON.stringify(addressData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                addressModal.hide();
                location.reload(); // 刷新页面显示更新的地址
            } else {
                alert('更新地址失败：' + data.message);
            }
        })
        .catch(error => {
            console.error('Error updating address:', error);
            alert('更新地址失败，请稍后再试。');
        });
    }

    // 编辑地址函数
    function editAddress(addressId) {
        // 从页面中获取地址数据并填充表单
        const addressCard = document.querySelector(`[data-address-id="${addressId}"]`);
        if (addressCard) {
            const addressText = addressCard.querySelector('.card-text').textContent.trim();
            
            isEditingAddress = true;
            currentAddressId = addressId;
            addressModalTitle.textContent = '编辑地址';
            
            document.getElementById('addressText').value = addressText;
            document.getElementById('isDefault').checked = addressCard.querySelector('.badge') !== null;
            
            addressModal.show();
        }
    }

    // 设为默认地址函数
    function setDefaultAddress(addressId) {
        if (confirm('确定要设置此地址为默认地址吗？')) {
            fetch(`/profile/address/set-default/${addressId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    [csrfHeader]: csrfToken
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    location.reload(); // 刷新页面显示更新的默认地址
                } else {
                    alert('设置默认地址失败：' + data.message);
                }
            })
            .catch(error => {
                console.error('Error setting default address:', error);
                alert('设置默认地址失败，请稍后再试。');
            });
        }
    }

    // 删除地址函数
    function deleteAddress(addressId) {
        if (confirm('确定要删除此地址吗？此操作不可恢复！')) {
            fetch(`/profile/address/delete/${addressId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    [csrfHeader]: csrfToken
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    location.reload(); // 刷新页面移除已删除的地址
                } else {
                    alert('删除地址失败：' + data.message);
                }
            })
            .catch(error => {
                console.error('Error deleting address:', error);
                alert('删除地址失败，请稍后再试。');
            });
        }
    }
}); 